package org.jfonia.connect5.gui;

import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JComponent;
import org.jfonia.connect5.basics.MutableValueNode;
import org.jfonia.connect5.basics.Node;
import org.jfonia.connect5.basics.Observer;

/**
 * @author wijnand.schepens@hogent.be
 */
public class DragHandle extends JComponent implements Observer, MouseListener, MouseMotionListener
{
	final int HALFSIZE = 4;
	
	MutableValueNode<Integer> xNode, yNode;

	Point dragStartClickLocation = null;
	Point dragStartLocation = null;

	public DragHandle(MutableValueNode<Integer> xNode, MutableValueNode<Integer> yNode)
	{
		this.xNode = xNode;
		this.yNode = yNode;
		xNode.addObserver(this);
		yNode.addObserver(this);
		this.addMouseListener(this);
		this.addMouseMotionListener(this);

		setSize(2*HALFSIZE, 2*HALFSIZE);
		updateLocation();
	}

	public void onNotify(Object source)
	{
		//updateBounds();
		repaint();
	}


	public void updateLocation()
	{
		System.out.println("updateLocation called x=" + xNode.getValue() + ", y=" + yNode.getValue());
		this.setLocation(xNode.getValue() - HALFSIZE, yNode.getValue() - HALFSIZE);
	}

//	@Override
//	public void setLocation(Point p)
//	{
//		super.setLocation(p);
//		System.out.println("setLocation called");
//	}
	
//	public void paint(Graphics2D g)
//	{
//		int x = xNode.getValue();
//		int y = yNode.getValue();
//		g.fillRect(x - 2, y - 2, 4, 4);
//	}

	@Override
	public void paintComponent(Graphics g)
	{
		updateLocation();
		int x = HALFSIZE; // xNode.getValue();
		int y = HALFSIZE; // yNode.getValue();
		g.fillRect(x - HALFSIZE, y - HALFSIZE, 2*HALFSIZE+1, 2*HALFSIZE+1);
	}


	public void mouseClicked(MouseEvent e)
	{
		
	}

	public void mousePressed(MouseEvent e)
	{
		dragStartLocation = this.getLocation();
		dragStartClickLocation = e.getLocationOnScreen();
	}

	public void mouseReleased(MouseEvent e)
	{}

	public void mouseEntered(MouseEvent e)
	{}

	public void mouseExited(MouseEvent e)
	{}

	public void mouseDragged(MouseEvent e)
	{
		int x = e.getLocationOnScreen().x - dragStartClickLocation.x + dragStartLocation.x;
		int y = e.getLocationOnScreen().y - dragStartClickLocation.y + dragStartLocation.y;
		xNode.setValue(x);
		yNode.setValue(y);
	}

	public void mouseMoved(MouseEvent e)
	{
		
	}

}
